<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>我的目标记录</title>
  <script type="text/javascript" src="{{env('CDN_RESOURCE')}}/js/mobile/rem.js"></script>
  <link href="{{env('CDN_RESOURCE')}}/mobile/campaign/achievement/css/achievement.css?v={{config('app.version')}}" rel="stylesheet" type="text/css">
  <script type="text/javascript">window.CDN_RESOURCE = "{{env('CDN_RESOURCE')}}"</script>
</head>
<body>
<header>
  <div class="progress-circle">
    <svg class="circle" xmlns="http://www.w3.org/2000/svg">
      <circle class="back"></circle>
      <circle class="prog"></circle>
    </svg>
    <svg class="end" xmlns="http://www.w3.org/2000/svg">
      <circle class="in"></circle>
      <circle class="out"></circle>
    </svg>
    <div class="text">
      <div class="title">已完成</div>
      <div class="percentage" data-progress="0" data-currnet="0"></div>
      <div class="date" id="target-finish-time"></div>
      <div class="target"></div>
    </div>
    <script>
      document.querySelector('.progress-circle > .circle').setAttribute('width', 226 * rem + 'px')
      document.querySelector('.progress-circle > .circle').setAttribute('height', 226 * rem + 'px')
      document.querySelector('.progress-circle > .circle > .back').setAttribute('cx', 113 * rem + 'px')
      document.querySelector('.progress-circle > .circle > .back').setAttribute('cy', 113 * rem + 'px')
      document.querySelector('.progress-circle > .circle > .back').setAttribute('r', 110 * rem + 'px')
      document.querySelector('.progress-circle > .circle > .prog').setAttribute('cx', 113 * rem + 'px')
      document.querySelector('.progress-circle > .circle > .prog').setAttribute('cy', 113 * rem + 'px')
      document.querySelector('.progress-circle > .circle > .prog').setAttribute('r', 110 * rem + 'px')
      document.querySelector('.progress-circle > .circle').style.strokeWidth = 6 * rem + 'px'

      document.querySelector('.progress-circle > .end').setAttribute('width', 22 * rem + 'px')
      document.querySelector('.progress-circle > .end').setAttribute('height', 22 * rem + 'px')
      document.querySelector('.progress-circle > .end > .in').setAttribute('cx', 11 * rem + 'px')
      document.querySelector('.progress-circle > .end > .in').setAttribute('cy', 11 * rem + 'px')
      document.querySelector('.progress-circle > .end > .in').setAttribute('r', 6 * rem + 'px')
      document.querySelector('.progress-circle > .end > .out').setAttribute('cx', 11 * rem + 'px')
      document.querySelector('.progress-circle > .end > .out').setAttribute('cy', 11 * rem + 'px')
      document.querySelector('.progress-circle > .end > .out').setAttribute('r', 11 * rem + 'px')
      document.querySelector('.progress-circle > .circle').style.strokeWidth = 6 * rem + 'px'
    </script>
  </div>
  <div class="progress">
    <div class="done">
      <div class="num"><span class="big"></span><span class="small"></span></div>
      <div class="text">已完成(节)</div>
    </div>
    <div class="line"></div>
    <div class="remain">
      <div class="num"></div>
      <div class="text">截止天数</div>
    </div>
    <div class="line"></div>
    <div class="advise">
      <div class="num"></div>
      <div class="text">每周建议(节)</div>
    </div>
  </div>
  <span class="circle-1"></span>
  <span class="circle-2"></span>
</header>
<main>
  <div class="title">可获奖励</div>
  <div class="award" id="award"></div>
  <div class="title">打卡记录</div>
  <div class="record" id="record"></div>
  <div class="use-case">
    <span class="completed">已完成</span>
    <span class="forget">待打卡</span>
    <span class="undone">待上课</span>
  </div>
  <div class="buttons">
    <button id="renew-achievement" class="blue" style="display: none;" onclick="window.location = '/wx/achievement/new'">重设目标</button>
    <button id="finish-achievement" class="blue" style="display: none;">完成目标</button>
    {{--<button class="white">领取奖励</button>--}}
  </div>
</main>
<div class="msgbox-mask" id="msgbox-mask" style="display: none;">
  <div class="msgbox" id="msgbox">
    <div id="re-clock-success" style="display: none;">
      <div class="tick-on"></div>
      <div class="title">补卡成功</div>
    </div>
    <div id="normal-clock" style="display: none;">
      <div class="title">正常打卡</div>
      <div class="content">是否要重发模版消息，重新打卡？</div>
      <div class="buttons">
        <button class="white" onclick="hiddenMsgBox()">不了</button>
        <button class="blue" id="reminder">好的</button>
      </div>
    </div>
    <div id="re-clock-msgbox" style="display: none;">
      <div class="title">打卡已过期</div>
      <div class="content">是否要补卡？</div>
      <div class="buttons">
        <button class="white" onclick="hiddenMsgBox()">不了</button>
        <button class="blue" id="re-clock">直接补打卡</button>
      </div>
    </div>
    <div id="achievement-finish-tip" style="display: none;">
      <div class="tick-on"></div>
      <div class="title">请先完成所有打卡</div>
    </div>
    <div id="achievement-finish" style="display: none;">
      <div class="tick-on"></div>
      <div class="title">目标完成</div>
      <div class="award">
        <div class="item top-left ok">
          <img src="{{env('CDN_RESOURCE')}}/mobile/campaign/achievement/img/award-1.png">
          <div class="text">现金优惠券</div>
        </div>
        <div class="item top-right ok">
          <img src="{{env('CDN_RESOURCE')}}/mobile/campaign/achievement/img/award-2.png">
          <div class="text">目标达成证书</div>
        </div>
        <div class="item bottom-left ok">
          <img src="{{env('CDN_RESOURCE')}}/mobile/campaign/achievement/img/award-3.png">
          <div class="text">单词卡</div>
        </div>
        <div class="item bottom-right ok">
          <img src="{{env('CDN_RESOURCE')}}/mobile/campaign/achievement/img/award-4.png">
          <div class="text">勤奋徽章</div>
        </div>
      </div>
    </div>
  </div>
</div>
<script type="text/javascript" src="{{env('CDN_RESOURCE')}}/js/moment.min.js"></script>
<script type="text/javascript" src="https://static-app.97kid.com/wx/js/zepto.min.js"></script>
<script type="text/javascript" src="{{env('CDN_RESOURCE')}}/js/mobile/Zepto_fx_methods.js"></script>
<script type="text/javascript" src="{{env('CDN_RESOURCE')}}/js/mobile/login.js"></script>
<script type="text/javascript" src="{{env('CDN_RESOURCE')}}/js/AV.analytics.js"></script>
<script>
  (function() {
    var analytics = AV.analytics({
      appId: 'antYy9lOFi5mkU9QKjtYmRLM-gzGzoHsz',
      appKey: 'jqyWxLyobpsmdwsJddJlDheb'
    });
    var account = new Account({
      closeBtn: false,
      loginFirst: true
    })

    init()
    function init () {
      account.getUserInfo(function (err, user) {
        if (!err) {
          account.ajax({
            type: 'GET',
            path: '/s/achievements/current',
            success: function (data) {
              var targetFinishTime = moment(data.targetFinishTime*1000),
                startTime = moment(data.startTime*1000),
                finishedLessonCount = data.finishedLessonCount,
                targetLessonCount = data.targetLessonCount,
                gifts = data.gifts;

              $('#target-finish-time').text(targetFinishTime.format("MM月D日"))
              $('.progress > .done > .num > .big').text(finishedLessonCount)
              $('.progress > .done > .num > .small').text(targetLessonCount)
              $('.progress-circle > .text > .target').text(targetLessonCount)
              $('.progress > .remain > .num').text(targetFinishTime.diff(moment(), 'days'))
              var targetLessonCountWeeks = Math.ceil(targetLessonCount / Math.max(targetFinishTime.diff(startTime, 'weeks'), 1)),
                computedLessonCountWeeks = Math.ceil((targetLessonCount-finishedLessonCount)/Math.max(targetFinishTime.diff(moment(), 'weeks'), 1))
              $('.progress > .advise > .num').text(Math.max(computedLessonCountWeeks, targetLessonCountWeeks));
              var awardHTML = ''
              for (var i = 0; i < gifts.length && i < 4; i ++) {
                var gift = gifts[i]
                awardHTML += '<div class="item">' +
                  '             <img src="' + CDN_RESOURCE + '/mobile/campaign/achievement/img/award-' + gift.giftId + '.png">' +
                  '             <div class="text">' + gift.name + '</div>' +
                  '           </div>'
              }
              document.querySelector('#award').innerHTML = awardHTML
              if (finishedLessonCount >= targetLessonCount) {
                $('#renew-achievement').hide()
                $('#finish-achievement').show()
              } else {
                $('#renew-achievement').show()
                $('#finish-achievement').hide()
              }
            },
            error: function (err) {
              $.toastAlert(err.message, 2)
              window.location.href = '/wx/achievement/new'
            }
          })
          account.ajax({
            type: 'GET',
            path: '/s/achievements/current/clocks',
            success: function (data) {
              window.studentAchievementId = data.studentAchievementId;
              renderProgress(data.finishedLessonCount, data.targetLessonCount)
              renderRecord(data.clockInDetail, data.targetLessonCount)
            },
            error: function (err) {
              $.toastAlert(err.message, 2)
              window.location.href = '/wx/achievement/new'
            }
          })
        }
      })
    }
    function renderProgress (finishedLessonCount, targetLessonCount) {
      var end = document.querySelector('.progress-circle > .end')
      var prog = document.querySelector('.progress-circle > .circle > .prog')
      var percentage = document.querySelector('.progress-circle > .text > .percentage')
      var start = new Date().getTime()
      prog.style.strokeDasharray = ((finishedLessonCount / targetLessonCount) * 220 * rem * Math.PI) + 'px, 999999px'
      percentage.dataset.progress = finishedLessonCount

      var x = ((110 + 110 * Math.cos(((finishedLessonCount * 360 / targetLessonCount) - 270) * Math.PI / 180) - 11) + 3) * rem
      var y = ((110 + 110 * Math.sin(((finishedLessonCount * 360 / targetLessonCount) - 270) * Math.PI / 180) - 11) + 3) * rem
      end.style.webkitTransform = 'translate(' + x + 'px, ' + y + 'px)'
      end.style.transform = 'translate(' + x + 'px, ' + y + 'px)'
      end.style.visibility = 'visible'

      setTimeout(function () {
        var now = (new Date().getTime()) - start
        var progress = now / 700,
          count = Math.floor(finishedLessonCount * progress)
        percentage.dataset.current = count === 0 ? '0' : (count > 9 ? count : '0' + count)
        if (progress < 1) setTimeout(arguments.callee, 10)
      }, 10)
    }
    function renderRecord(records, targetLessonCount) {
      var recordHTML = '';
      var allClockIn = true;
      for (var i = 0; i < targetLessonCount; i++) {
        if (records[i] && records[i].clockIn == 0) allClockIn = false;
        recordHTML += i > records.length - 1 ? '<span class="empty">' + (i + 1) + '</span>' : (records[i].clockIn === 0 ? '<span class="warn" clock-id="' + records[i].clockId + '" schedule-begin-at="' + records[i].scheduleBeginAt + '">' + (i + 1) + '</span>' : '<span class="ok"></span>')
      }
      if (records.length >= targetLessonCount) {
        $('#finish-achievement').off('click').on('click', function () {
          if (allClockIn) {
            account.ajax({
              type: 'POST',
              path: '/s/achievements/finish',
              success: function () {
                showMsgBox('achievement-finish');
                $('#finish-achievement').hide();
                $('#renew-achievement').text('设定新目标').show();
                analytics.send({
                  event: 'achievement-finish',
                  attr: {
                    achievementId: window.studentAchievementId
                  }
                });
              },
              error: function (err) {
                $.toastAlert(err.message, 2);
              }
            })
          } else {
            showMsgBox('achievement-finish-tip');
          }
        })
      }
      $('#record').empty().append(recordHTML)
      $('#record > span').off('click').on('click', function () {
        var clockId = $(this).attr('clock-id')
        if (clockId) {
          var scheduleBeginAt = moment($(this).attr('schedule-begin-at')*1000).add(1, 'weeks').endOf('day')
          if (token) {
            // 在小程序里
            if (moment().isBefore(scheduleBeginAt)) {
              // 在正常打卡时间内
              // 提示去微信打卡, 重发模板消息
              showMsgBox('normal-clock')
              $('#reminder').off('click').on('click', function () {
                account.ajax({
                  type: 'POST',
                  path: '/s/achievements/clocks/' + clockId + '/reminder',
                  success: function () {
                    analytics.send({
                      event: 'clock-reminder',
                      attr: {
                        clockId: clockId
                      }
                    });
                    $.toastAlert('发送成功')
                    hiddenMsgBox()
                  },
                  error: function (err) {
                    $.toastAlert(err.message, 2)
                  }
                })
              })
            } else {
              // 弹出补卡提示
              showMsgBox('re-clock-msgbox')
              $('#re-clock').off('click').on('click', function () {
                account.ajax({
                  type: 'POST',
                  path: '/s/achievements/clocks/' + clockId,
                  success: function () {
                    analytics.send({
                      event: 'clock-supplement',
                      attr: {
                        clockId: clockId
                      }
                    });
                    showMsgBox('re-clock-success')
                    init()
                  },
                  error: function (err) {
                    $.toastAlert(err.message, 2)
                  }
                })
              })
            }
          } else {
            // 不在小程序里
            window.location.href = '/wx/achievement/clocks/' + clockId
          }
        }
      })
    }

    $('#msgbox').off('click').on('click', function (e) {
      e.stopPropagation()
    })
    $('#msgbox-mask').off('click').on('click', function (e) {
      e.stopPropagation()
      hiddenMsgBox()
    })
  })();

  function showMsgBox (msgboxId) {
    hiddenMsgBox()
    document.getElementById('msgbox-mask').style.display = 'block'
    document.getElementById(msgboxId).style.display = 'block'
  }
  function hiddenMsgBox () {
    document.getElementById('msgbox-mask').style.display = 'none'
    document.getElementById('re-clock-success').style.display = 'none'
    document.getElementById('normal-clock').style.display = 'none'
    document.getElementById('re-clock-msgbox').style.display = 'none'
    document.getElementById('achievement-finish-tip').style.display = 'none'
    document.getElementById('achievement-finish').style.display = 'none'
  }
</script>
</body>
</html>